package com.geeke.sys.controller;

import java.util.Collection;
import java.util.List;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.geeke.sys.entity.User;
import com.geeke.sys.vo.OnlineUserVo;
import com.geeke.utils.ResultUtil;
import com.geeke.utils.SessionUtils;
import com.google.common.collect.Lists;

@RestController
@RequestMapping(value = "/online")
public class OnlineUserController {
    
    @Autowired
    private SessionDAO sessionDAO;

    @PostMapping(value = { "" })
    public ResponseEntity<JSONObject> online() {
        Collection<Session> sessions = sessionDAO.getActiveSessions();
        List<OnlineUserVo> onlineUsers = Lists.newArrayList();
        for(Session session : sessions) {
            User user = SessionUtils.getUser(session);
            OnlineUserVo onlineUser = OnlineUserVo.fromUser(user); 
            onlineUser.setIp(session.getHost());
            onlineUser.setLoginTime(session.getStartTimestamp());
            onlineUser.setLastAccessTime(session.getLastAccessTime());
            onlineUser.setSessionId(session.getId().toString());
            onlineUsers.add(onlineUser);
        }
        return ResponseEntity.ok(ResultUtil.successJson(onlineUsers));
    }

    /**
     * 踢在线用户
     * 
     * @param model
     * @return
     */
    @GetMapping("/offline/{id}")
    public ResponseEntity<JSONObject> offline(@PathVariable("id") String sessionId) {
        Session session = sessionDAO.readSession(sessionId);// sessionId：在获取在线用户那里可以获取得到
        if (session != null) {
            session.stop();
            sessionDAO.delete(session);
        }
        return  ResponseEntity.ok(ResultUtil.successJson(sessionId));
    }

}
